package Server.security;


import Server.dao.*;
import Server.entity.Permissions;
import Server.entity.Role;
import Server.entity.RolePermissions;
import Server.entity.Users;
import Server.tool.EDcrypionUtils;
import Server.tool.HttpRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class UserRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(AuthorizingRealm.class);

    @Autowired
    private UsersDao usersDao;
    @Autowired
    private PermissionsDao permissionsDao;
    @Autowired
    private RequestLogDao requestLogDao;
    @Autowired
    private RolePermissionsDao rolePermissionsDao;



    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Users fspUser = (Users) principalCollection.getPrimaryPrincipal();
        Collection<String> roles = new LinkedHashSet<>();
        Set<String> permissions = new LinkedHashSet<>();

        Role userRoles=fspUser.getRole();
        roles.add(userRoles.getUuid());
        List<RolePermissions> rolePermissions = rolePermissionsDao.findByRole(userRoles);

        //根据角色找权限
        List<Permissions> fspRolePermissionsList = new LinkedList<>();

        for(RolePermissions roper : rolePermissions){
            fspRolePermissionsList.add(roper.getPermissions());
        }

        for(Permissions fspRolePermissions : fspRolePermissionsList){
            permissions.add(fspRolePermissions.getCode());
        }


        authorizationInfo.addRoles(roles);

        authorizationInfo.addStringPermissions(permissions);

        return authorizationInfo;
    }

    //登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1，获得前端传值

        String username = (String) authenticationToken.getPrincipal();
        Users user = usersDao.findByUsername(username);
        if(user==null||user.getStatus().equals(Users.Status.NO)){
            user=null;
        }
        if (user == null) {
            //没找到帐号
            throw new UnknownAccountException();
        }

        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashIterations(10);
        matcher.setHashAlgorithmName("md5");
        this.setCredentialsMatcher(matcher);

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), "");
        //盐
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(EDcrypionUtils.key));
        //将用户信息放入session中
        SecurityUtils.getSubject().getSession().setTimeout(-1000l);
        SecurityUtils.getSubject().getSession().setAttribute("Users", user);
        return authenticationInfo;
    }

    //加密
    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(EDcrypionUtils.shiroPassword("123456") );
        /*
new Md5Hash("123456","GGZEServer",10).toString()
        Md5Hash md5Hash = new Md5Hash("123456","GGZEServer",10);
*/
        /*Base64.encodeToString("123456".getBytes());
        System.out.println(new Md5Hash("123456", EDcrypionUtils.key,EDcrypionUtils.nbm).toString());
        System.out.println(Base64.decodeToString("MTIzNDU2".getBytes()));*/
 /*       String CorpID = "HFJS004192";// 账户名
        String Pwd = "604192@";// 密码
        String Mobile = "15771929325";
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss");
        String send_time = dateTimeFormatter1.format(now);
        String now_time = dateTimeFormatter2.format(now);
        System.out.println(now_time);
        String Content = "您正在修改登陆密码。本次验证码为888888切勿泄露给他人【凯诺商城】";
        String send_content = URLEncoder.encode(
                Content.replaceAll("<br/>", " "), "GBK");// 发送内容
        String url ="https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID="
                + CorpID + "&Pwd=" + Pwd + "&Mobile=" + Mobile + "&Content="
                + send_content + "&Cell=&SendTime=" + send_time;
        String result =  HttpRequest.sendGet(url);
        System.out.println(result);*/
    }

}
